package com.mes.system.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import com.mes.common.dao.BasicDao;
import com.mes.system.dao.iface.IRoleDao;
import com.mes.system.domain.EmployeeRole;
import com.mes.system.domain.Role;

@Repository
public class RoleDao extends BasicDao<Role> implements IRoleDao {
	
	/**
	 * 根据人员的Uid获得该人员对应的角色列表
	 * @param employeeUid
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<Role> getRolesByEmployeeUid(String employeeUid) throws Exception {
		List<Role> roles = new ArrayList<Role>();
		
		Session session = this.getSessionFactory().getCurrentSession();
		String hql = "from " + EmployeeRole.class.getName() + " where employeeUid = '" + employeeUid + "'";
		Query query = session.createQuery(hql);
		List<EmployeeRole> employeeRoles = query.list();
		if(employeeRoles != null && employeeRoles.size() > 0){
			for(EmployeeRole er : employeeRoles){
				Role role = this.getById(er.getRoleUid());
				roles.add(role);
			}
		}
		
		return roles;
	}
	
	@Override
	public void updateBDFRole(com.bstek.bdf2.core.model.Role bdfRole) throws Exception {
		Session session = this.getSessionFactory().getCurrentSession();
		try {
			session.update(bdfRole);
		} finally {
			session.flush();
		}
		
	}

	@Override
	public void deleteBDFRole(com.bstek.bdf2.core.model.Role bdfRole) throws Exception {
		Session session = this.getSessionFactory().getCurrentSession();
		try {
			session.delete(bdfRole);
		} finally {
			session.flush();
		}
		
	}

	@Override
	public void saveBDFRole(com.bstek.bdf2.core.model.Role bdfRole) throws Exception {
		Session session = this.getSessionFactory().getCurrentSession();
		try {
			session.save(bdfRole);
		} finally {
			session.flush();
		}
		
	}

	@Override
	public List<Role> getRolesNoEmployee(String employeeUid) throws Exception {
		Session session = this.getSessionFactory().getCurrentSession();
		String sql = "select * from s_role r where roleid not in "
				+ "(select roleid from s_employee_role where employeeid = ?)";
		
		SQLQuery query = session.createSQLQuery(sql).addEntity(Role.class);
		query.setString(0, employeeUid);
		List<Role> list = query.list();
		
		return list;
	}

	@Override
	public com.bstek.bdf2.core.model.Role getBdfRoleByName(String name) {
		Session session = this.getSessionFactory().getCurrentSession();
		String hql = "from com.bstek.bdf2.core.model.Role where name = ?";
		
		Query query = session.createQuery(hql);
		query.setString(0, name);
		List<com.bstek.bdf2.core.model.Role> list = query.list();
		
		if (list.size() > 0){
			return list.get(0);
		}else {
			return null;
		}
		
		
	}
	
}
